package com.czr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czr.constant.isLogin;
import com.czr.dao.entity.CzrUser;
import com.czr.util.TencentCosUtil;
import com.czr.vo.CzrUserVo;
import com.czr.dao.service.CzrUserService;
import com.czr.dto.*;
import com.czr.util.Md5;
import com.czr.vo.Result;
import io.swagger.annotations.*;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@Api(value = "用户管理", tags = "用户管理")
@RestController
@RequestMapping("/sso")
public class SsorController {

    @Autowired
    private CzrUserService userService;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;



    /**
     * 登录接口
     *
     * @param loginParam 包含登录所需参数的对象，如用户名和经过处理的密码
     * @return Result<Map<String, Object>> 登录结果，成功返回包含用户信息的Map，失败返回空Map
     */
    @isLogin
    @ApiOperation(value = "登录接口", notes = "登录接口")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginParam loginParam) {
        try {
            // 调用userService的login方法进行用户登录验证
            Result<Map<String, Object>> result = userService.login(loginParam.getUsername(), Md5.md52(loginParam.getPassword()),loginParam.getIsLoginType());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            // 登录遇到异常，返回失败结果
            return Result.fail();
        }

    }

    /**
     * 管理员登录接口。
     * 该接口用于管理员进行登录操作，通过接收登录参数，验证管理员身份，并返回登录结果。
     *
     * @param loginParam 登录参数，包含管理员用户名、密码和登录类型。
     * @return 返回登录结果，成功时包含登录信息，失败时返回错误信息。
     */
    @isLogin
    @ApiOperation(value = "管理后端-登录接口", notes = "管理后端-登录接口")
    @PostMapping("/adminLogin")
    public Result<Map<String, Object>> adminLogin(@RequestBody LoginParam loginParam) {
        try {
            // 调用userService的adminLogin方法进行登录验证，密码经过MD5加密处理。
            Result<Map<String, Object>> result = userService.adminLogin(loginParam.getUsername(), Md5.md52(loginParam.getPassword()),loginParam.getIsLoginType());
            return result;
        } catch (Exception e) {
            // 捕获登录过程中可能出现的异常，打印异常堆栈，并返回登录失败的结果。
            e.printStackTrace();
            return Result.fail();
        }

    }


    @isLogin
    @ApiOperation(value = "获取用户信息接口", notes = "登录接口")
    @ApiImplicitParams({
            //参数效验
            @ApiImplicitParam(name="token",value="登录凭证",required=true,dataType="String")
    })
    @GetMapping("/getUserInfo")
    public Result<Object> getUserInfo(@RequestParam @NonNull String token) {
        try {
            ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
            if (!StringUtils.isEmpty(valueOperations.get(token))) {
                JSONObject cacheToken = JSON.parseObject(valueOperations.get(token).toString());
                Result<Object> result = userService.getUserInfo(Integer.parseInt(cacheToken.get("id").toString()));
                return result;
            } else {
                return Result.success(202,"用户未登录或登录已失效！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
    }
    @isLogin
    @ApiOperation(value = "用户注册", notes = "用户注册")
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody RegParam regParam) {
        try {
            CzrUser czrUser=new CzrUser();
            BeanUtils.copyProperties(regParam, czrUser);
            Result<Map<String, Object>> result = userService.register(czrUser);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
    }
    @ApiOperation(value = "用户资料修改", notes = "用户资料修改")
    @PostMapping("/update")
    public Result<Map<String, Object>> update(@RequestBody RegParam regParam) {
        try {
            CzrUser czrUser=new CzrUser();
            BeanUtils.copyProperties(regParam, czrUser);
            Result<Map<String, Object>> result = userService.update(czrUser);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
    }
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @PostMapping("/updatePwd")
    public Result<Map<String, Object>> updatePwd(@RequestBody CzrUserVo czrUserVo, HttpServletRequest request) {
        try {
            ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
            Object object=valueOperations.get(request.getHeader("token"));
            if (!StringUtils.isEmpty(object)) {
                JSONObject cacheToken = JSON.parseObject(object.toString());
                czrUserVo.setId(cacheToken.getLong("id"));
                Result<Map<String, Object>> result = userService.updatePwd(czrUserVo);
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
        return null;
    }
//    @ApiOperation(value = "管理端-重置密码", notes = "管理端-重置密码")
//    @GetMapping("/updateAdminPwd")
//    public Result<Map<String, Object>> updateAdminPwd(@RequestParam Integer userId,@RequestParam String password, HttpServletRequest request) {
//        try {
//            ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
//            Object object=valueOperations.get(request.getHeader("token"));
//            if (!StringUtils.isEmpty(object)) {
//                JSONObject cacheToken = JSON.parseObject(object.toString());
//                Result<Map<String, Object>> result = userService.updateAdminPwd(userId,password,cacheToken);
//                return result;
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//        return null;
//    }
    @ApiOperation(value = "管理端-删除会员", notes = "管理端-删除会员")
    @GetMapping("/delAdmin")
    public Result<Map<String, Object>> delAdmin(@RequestParam Integer userId, HttpServletRequest request) {
        try {
            ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
            Object object=valueOperations.get(request.getHeader("token"));
            if (!StringUtils.isEmpty(object)) {
                Result<Map<String, Object>> result = userService.deladmin(userId);
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }
        return null;
    }


    @ApiOperation(value = "会员列表", notes = "会员列表")
    @PostMapping("/verify_list")
    public Result<Object> verify_list(@RequestBody Search search) {
        try {
            return userService.list(search);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail();
        }

    }
//    @ApiOperation(value = "会员审核", notes = "会员审核")
//    @ApiImplicitParams({
//            //参数效验
//            @ApiImplicitParam(name="userId",value="用户id",required=true,dataType="Integer"),
//            @ApiImplicitParam(name="status",value="审核状态（1 通过 2不通过）",required=true,dataType="Integer"),
//            @ApiImplicitParam(name="userLevel",value="会员级别 （1普通会员 2高级会员）",required=true,dataType="Integer"),
//            @ApiImplicitParam(name="usort",value="排序字段",required=false,dataType="Integer")
//    })
//    @GetMapping("/verify_update")
//    public Result<Map<String, Object>> verify_update(@RequestParam Long userId,Integer status,Integer userLevel,Integer usort) {
//        try {
//            Result<Map<String, Object>> result = userService.verify_update(userId,status,userLevel,usort);
//            return result;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//    }

//    @isLogin
//    @ApiOperation(value = "关于我们-查询", notes = "关于我们-查询")
//    @GetMapping("/about_select")
//    public Result<Object> about_select() {
//        try {
//            return userService.about_select();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//    }
//    @isLogin
//    @ApiOperation(value = "关于我们-修改", notes = "关于我们-修改")
//    @PostMapping("/about_update")
//    public Result<Object> about_update(@RequestBody String content) {
//        try {
//            return userService.about_update(content);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//    }
//    @isLogin
//    @ApiOperation(value = "腾讯云cos访问地址", notes = "腾讯云cos访问地址")
//    @ApiImplicitParams({
//            //参数效验
//            @ApiImplicitParam(name="fileName",value="上传后图片名称",required=true,dataType="String")
//    })
//    @GetMapping("/imgPath_wx")
//    public Result<Object> imgPath_wx(@RequestParam String fileName) {
//        try {
//            TencentCosUtil tencentCosUtil=new TencentCosUtil();
//             return Result.data(200,tencentCosUtil.imgFile_wx(fileName), "");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail();
//        }
//    }

}
